Source Code Viewer - Example 14 - PrimeMinisterForm

package name.matthewgreet.example14.form;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.beanutils.PropertyUtils;
import com.opensymphony.xwork2.TextProvider;

import name.matthewgreet.example14.annotation.AgeRange;
import name.matthewgreet.example14.annotation.DateRangeListConversion;
import name.matthewgreet.example14.annotation.IntegerInnerOuterRange;
import name.matthewgreet.example14.annotation.IntegerLocaleConversion;
import name.matthewgreet.example14.annotation.NoDateRangeOverlap;
import name.matthewgreet.example14.annotation.ShortRange;
import name.matthewgreet.example14.annotation.StartsWith;
import name.matthewgreet.example14.annotation.ToCapitalised;
import name.matthewgreet.example14.dto.DateRange;
import name.matthewgreet.example14.dto.Person;
import name.matthewgreet.example14.dto.PrimeMinisterDTO;
import name.matthewgreet.example14.dto.PrimeMinisterDTO.OtherCabinetPosition;
import name.matthewgreet.example14.dto.PrimeMinisterDTO.Party;
import name.matthewgreet.strutscommons.action.ValidationAware2;
import name.matthewgreet.strutscommons.annotation.DateConversion;
import name.matthewgreet.strutscommons.annotation.IntegerRange;
import name.matthewgreet.strutscommons.annotation.ManualParameterConversion;
import name.matthewgreet.strutscommons.annotation.MaxLength;
import name.matthewgreet.strutscommons.annotation.RemoveNullIntegerEntries;
import name.matthewgreet.strutscommons.annotation.Required;
import name.matthewgreet.strutscommons.annotation.ShortConversion;
import name.matthewgreet.strutscommons.annotation.Trim;
import name.matthewgreet.strutscommons.form.AbstractFormattableForm;
import name.matthewgreet.strutscommons.form.FormatResult;
import name.matthewgreet.strutscommons.form.ManualParameterConversionResult;
import name.matthewgreet.strutscommons.util.FieldParsedParameterList;

public class PrimeMinisterForm extends AbstractFormattableForm {
	private static final long serialVersionUID = -6937072630784482008L;
	
	@Trim
	@ToCapitalised
	@Required(messageKey = "validation.name.required")
	private String name;
	
	@DateConversion(format = "", messageKey = "validation.dateofbirth.conversion")
	@AgeRange(minAge = 30, minAgeMessageKey = "validation.dateofbirth.minage", maxAge = 150, maxAgeMessageKey = "validation.dateofbirth.maxage")
	private Date dateOfBirth;
	
	@ManualParameterConversion
	private List<Person> children = new ArrayList<>();
	
	@Required(messageKey = "validation.wikipediaentry.required")
	@StartsWith(startsWith = "https://en.wikipedia.org/", messageKey = "validation.wikipediaentry.notwikipedia")
	private String wikipediaEntry;
	
	
	private Party party;
	
	@MaxLength(maxLength = 50, messageKey = "validation.constituency.maxlength")
	private String constituency;
	
	@IntegerLocaleConversion(messageKey = "validation.bestconstituencymajority.conversion")
	@IntegerRange(min = 0, max = 150000, messageKey = "validation.bestconstituencymajority.range")
	private Integer bestConstituencyMajority;
	
	@ShortConversion(messageKey = "validation.bestconstituencyyear.conversion")
	@ShortRange(min = 1950, max = 2100, messageKey = "validation.bestconstituencyyear.range")
	private Short bestConstituencyYear;
	
	private Set<OtherCabinetPosition> otherCabinetPositions;
	

	@DateRangeListConversion(format = "", messageKey = "validation.termsofoffice.conversion")
	@NoDateRangeOverlap(messageKey = "validation.termsofoffice.overlap")
	private List<DateRange> termsOfOffice; // Non overlap check
	
	@IntegerLocaleConversion(messageKey = "validation.maxseatswon.conversion")
	@IntegerInnerOuterRange(outerMin = 1, tooLowMessageKey = "validation.maxseatswon.toolow", 
	                        innerMin = 325, warningLowMessageKey = "validation.maxseatswon.warningtoolow",
	                        innerMax = 425, warningHighMessageKey = "validation.maxseatswon.warningtoohigh",
	                        outerMax = 707, tooHighMessageKey = "validation.maxseatswon.toohigh")
	private Integer maxSeatsWon;
	
	@ShortConversion(messageKey = "validation.maxseatsyear.conversion")
	@ShortRange(min = 1950, max = 2100, messageKey = "validation.maxseatsyear.range")
	private Short maxSeatsYear;

	@IntegerLocaleConversion(messageKey = "validation.otherseatswon.conversion")
	@IntegerInnerOuterRange(outerMin = 1, tooLowMessageKey = "validation.otherseatswon.toolow", 
	                        innerMin = 325, warningLowMessageKey = "validation.otherseatswon.warningtoolow",
	                        innerMax = 425, warningHighMessageKey = "validation.otherseatswon.warningtoohigh",
	                        outerMax = 707, tooHighMessageKey = "validation.otherseatswon.toohigh")
	@RemoveNullIntegerEntries
	private List<Integer> otherSeatsWon = new ArrayList<>();
	

	public PrimeMinisterForm() {
		// Default constructor is required
	}
	
	public PrimeMinisterForm(PrimeMinisterDTO primeMinister) throws Exception {
		// Uses commons-beanutils
		if (primeMinister != null) {
			PropertyUtils.copyProperties(this, primeMinister);
		}
	}

	
	private List<String> parseStringParameters(Map<String,FieldParsedParameterList> unprocessedParameters, String parameterName) {
		FieldParsedParameterList parameter;
		List<String> result;
		
		result = new ArrayList<>();
		parameter = unprocessedParameters.get(parameterName);
		if (parameter != null) {
			result = parameter.getMultipleParameterValues();
		} else {
			result = new ArrayList<>();
		}
		return result;
	}
	
	@Override
	public FormatResult format() {
		FormatResult result;
		List<String> childNames, childBirthYears;
		
		childNames = new ArrayList<>();
		childBirthYears = new ArrayList<>();
		for (Person child: children) {
			childNames.add(child.getName());
			childBirthYears.add(Short.toString(child.getBirthYear()));
		}
		
		result =  new FormatResult();
		result.getFormattedMultipleFieldValues().put("childName", childNames);
		result.getFormattedMultipleFieldValues().put("childBirthYear", childBirthYears);
		return result;
	}

	@Override
	public ManualParameterConversionResult manualParameterConvert(Map<String,FieldParsedParameterList> unprocessedParameters,
			ValidationAware2 validationAware, TextProvider textProvider) {
		Person child;
		ManualParameterConversionResult result;
		List<String> childNames, childBirthYearTexts;
		String childName, childBirthYearText;
		Short childBirthYear;
		boolean missingYear, invalidYear;
		
		result = new ManualParameterConversionResult();
		
		childNames = parseStringParameters(unprocessedParameters, "childName");
		childBirthYearTexts = parseStringParameters(unprocessedParameters, "childBirthYear");
		
		missingYear = false;
		invalidYear = false;
		children = new ArrayList<>();
		for (int i = 0; i < childNames.size(); i++) {
			childName = childNames.get(i);
			if (childName == null || childName.length() == 0) {
				// Ignore superfluous, blank entry 
				continue;
			}
			childBirthYearText = (i < childBirthYearTexts.size())?childBirthYearTexts.get(i):null;
			if (childBirthYearText == null || childBirthYearText.length() == 0) {
				missingYear = true;
				continue;
			}
			try {
				childBirthYear = Short.parseShort(childBirthYearText);
				child = new Person();
				child.setName(childName);
				child.setBirthYear(childBirthYear);
				children.add(child);
			}
			catch (NumberFormatException e) {
				invalidYear = true;
				continue;
			}
			
		}
		
		if (missingYear) {
			validationAware.addActionError("The birth year is required for each child");
		}
		if (invalidYear) {
			validationAware.addActionError("One of the birth years is not a valid year");
		}
		if (missingYear || invalidYear) {
			result.getFailedMultipleParameterNames().add("childName");
			result.getFailedMultipleParameterNames().add("childBirthYear");
		} else {
			result.getProcessedMultipleParameterNames().add("childName");
			result.getProcessedMultipleParameterNames().add("childBirthYear");
		}
		return result;
	}
	
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	public Date getDateOfBirth() {
		return dateOfBirth;
	}
	public void setDateOfBirth(Date dateOfBirth) {
		this.dateOfBirth = dateOfBirth;
	}

	public List<Person> getChildren() {
		return children;
	}
	public void setChildren(List<Person> children) {
		this.children = children;
	}

	public String getWikipediaEntry() {
		return wikipediaEntry;
	}
	public void setWikipediaEntry(String wikipediaEntry) {
		this.wikipediaEntry = wikipediaEntry;
	}
	
	
	public Party getParty() {
		return party;
	}
	public void setParty(Party party) {
		this.party = party;
	}

	public String getConstituency() {
		return constituency;
	}
	public void setConstituency(String constituency) {
		this.constituency = constituency;
	}

	public Integer getBestConstituencyMajority() {
		return bestConstituencyMajority;
	}
	public void setBestConstituencyMajority(Integer bestConstituencyMajority) {
		this.bestConstituencyMajority = bestConstituencyMajority;
	}

	public Short getBestConstituencyYear() {
		return bestConstituencyYear;
	}
	public void setBestConstituencyYear(Short bestConstituencyYear) {
		this.bestConstituencyYear = bestConstituencyYear;
	}

	public Set<OtherCabinetPosition> getOtherCabinetPositions() {
		return otherCabinetPositions;
	}
	public void setOtherCabinetPositions(Set<OtherCabinetPosition> otherCabinetPositions) {
		this.otherCabinetPositions = otherCabinetPositions;
	}

	
	public List<DateRange> getTermsOfOffice() {
		return termsOfOffice;
	}
	public void setTermsOfOffice(List<DateRange> termsOfOffice) {
		this.termsOfOffice = termsOfOffice;
	}

	public Integer getMaxSeatsWon() {
		return maxSeatsWon;
	}
	public void setMaxSeatsWon(Integer maxSeatsWon) {
		this.maxSeatsWon = maxSeatsWon;
	}

	public Short getMaxSeatsYear() {
		return maxSeatsYear;
	}
	public void setMaxSeatsYear(Short maxSeatsYear) {
		this.maxSeatsYear = maxSeatsYear;
	}
	
	public List<Integer> getOtherSeatsWon() {
		return otherSeatsWon;
	}
	public void setOtherSeatsWon(List<Integer> otherSeatsWon) {
		this.otherSeatsWon = otherSeatsWon;
	}

	
	@Override
	public String toString() {
		final int maxLen = 10;
		return "PrimeMinisterForm [" + (name != null ? "name=" + name + ", " : "")
				+ (dateOfBirth != null ? "dateOfBirth=" + dateOfBirth + ", " : "")
				+ (children != null ? "children=" + children.subList(0, Math.min(children.size(), maxLen)) + ", " : "")
				+ (wikipediaEntry != null ? "wikipediaEntry=" + wikipediaEntry + ", " : "")
				+ (party != null ? "party=" + party + ", " : "")
				+ (constituency != null ? "constituency=" + constituency + ", " : "")
				+ (bestConstituencyMajority != null ? "bestConstituencyMajority=" + bestConstituencyMajority + ", "
						: "")
				+ (bestConstituencyYear != null ? "bestConstituencyYear=" + bestConstituencyYear + ", " : "")
				+ (otherCabinetPositions != null ? "otherCabinetPositions=" + otherCabinetPositions + ", " : "")
				+ (termsOfOffice != null
						? "termsOfOffice=" + termsOfOffice.subList(0, Math.min(termsOfOffice.size(), maxLen)) + ", "
						: "")
				+ (maxSeatsWon != null ? "maxSeatsWon=" + maxSeatsWon + ", " : "")
				+ (maxSeatsYear != null ? "maxSeatsYear=" + maxSeatsYear + ", " : "")
				+ (otherSeatsWon != null
						? "otherSeatsWon=" + otherSeatsWon.subList(0, Math.min(otherSeatsWon.size(), maxLen))
						: "")
				+ "]";
	}

}